const koa = require('koa')
const router = require('koa-router')()
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/users');

// 创建连接 
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
    // we're connected!
    console.log('连接成功')
});

// express  koa  egg

const app = new koa()

app.use(router.routes())
app.use(router.allowedMethods())

// 1. 创建模型 （要求将来要添加到数据库中数据的格式）
var kittySchema = mongoose.Schema({
    name: String
});

var stuModle = mongoose.model('test', kittySchema, 'test')

// mongoose.model(表名, 格式)
// var stuModle = mongoose.model('test', kittySchema, 'test')

// new stuModle({ name: '马八' }).save()


router.get('/list', async (ctx, next) => {
    ctx.body = "我是查找接口"
    stuModle.find({ name: "zhangsan" }, (err, data) => {
        console.log(data)
    })
})


router.get('/add', async (ctx, next) => {
    ctx.body = "我是增加接口"
    new stuModle({ name: '张三' }).save()
})

router.delete('/del', async (ctx, next) => {
    ctx.body = "我是删除接口"
    stuModle.deleteOne({ name: '张三' }, () => {
        console.log('删除成功')
    })
})

router.put('/edit', async (ctx, next) => {
    ctx.body = "我是编辑接口"
    stuModle.updateOne({ name: '马八更新' }, { name: '马八更新11111111' }, () => {
        console.log('编辑成功')
    })
})


app.listen(3000, () => {
    console.log('第一次使用koa')
})


// let arr = {
//     data: [
//         {
//             name: "张三",
//             shop: "三只松鼠",
//             order: [
//                 '11111111',
//                 '22222222'
//             ]
//         },
//         {
//             name: "李四",
//             shop: "三只松鼠",
//             order: [
//                 '11111111',
//                 '22222222'
//             ]
//         }
//     ]
// }
